package com.gopay.bis.manager.bank.Wap;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.ceb.ebank.CebB2cMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.WapPayManagerRemoteService;
import com.gopay.remote.bank.businesses.BankService;

public class CebWapB2cManager implements WapPayManagerRemoteService{
private static final String SEPARATOR = "~|~";
	
	@Resource(name = "cebB2cBankServiceClient")
	private BankService cebB2cBankServiceClient;
	
	@Resource(name = "cebB2cBankServiceClientHna")
	private BankService cebB2cBankServiceClientHna;
	
	@Resource(name = "cebConfig")
	private Map<String, String> cebConfig;
	private static Logger logger = LoggerFactory.getLogger(CebWapB2cManager.class);
	/**
	 * B2C签名
	 */
	@Override
	public Object sign(BaseMessage message) throws GopayException {
		CebB2cMessage cebB2cMessage = buildMessage(message);
		cebB2cMessage.setPlainMessage(buildPayPlainStr(cebB2cMessage));
		BankLogUtils.printB2CManagerSignSendLog(cebB2cMessage);
		String signVal;
		logger.error("sign send 11:" + ToStringBuilder.reflectionToString(cebB2cMessage, ToStringStyle.DEFAULT_STYLE));
		if(cebB2cMessage.isHna()){
			signVal = (String) cebB2cBankServiceClientHna.sign(cebB2cMessage);
		}else{
			logger.error("sign send 22:" + ToStringBuilder.reflectionToString(cebB2cMessage, ToStringStyle.DEFAULT_STYLE));
			signVal = (String) cebB2cBankServiceClient.sign(cebB2cMessage);
		}
		cebB2cMessage.setSignMessage(signVal);
		BankLogUtils.printB2CManagerSignReturnLog(message);
		return cebB2cMessage;
	}
	
	/**
	 * B2C验签
	 */
	@Override
	public Object verify(BaseMessage msg) throws GopayException {
		// 调用远程接口请求签名数据
		CebB2cMessage message = (CebB2cMessage) msg;
		BankLogUtils.printB2CManagerSignSendLog(message);
		boolean isVerify; 
		if(message.isHna()){
			isVerify = (Boolean) cebB2cBankServiceClientHna.verify(message);
		}else{
			isVerify = (Boolean) cebB2cBankServiceClient.verify(message);
		}
		//验签成功后为通知银行拼装明文串和官文串
		if(isVerify){
			String notifyStr = buildNotifyBankInfo(message);
			CebB2cMessage notifyMessage = new CebB2cMessage();
			notifyMessage.setPlainMessage(notifyStr);
			notifyMessage.setBank(BankConstants.BANK_LOGO_CEB);
			String signVal = (String) cebB2cBankServiceClient.sign(message);
			message.setNotifyPlain(notifyStr);
			message.setNotifySign(signVal);
		}
		BankLogUtils.printB2CManagerVerifyReturnLog(message, isVerify);
		return isVerify;
	}

	@Override
	public Object dayend(BaseMessage arg0) throws GopayException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * B2C单笔订单查询
	 */
	@Override
	public Object query(Object obj) throws GopayException {
		CebB2cMessage cebB2cMessage = (CebB2cMessage) obj;
		buildQueryMessage(cebB2cMessage);
		if(BisPayCheckUtils.checkExternalOrderID(cebB2cMessage.getOrderId())){
			cebB2cMessage.setOriginalorderId(cebB2cMessage.getOrderId());
			cebB2cMessage.setOriginalTransDateTime(cebB2cMessage.getOrderDate());
		}
		cebB2cMessage.setPlainMessage(buildQueryPlainStr(cebB2cMessage));
		BankLogUtils.printB2CManagerQuerySendLog(cebB2cMessage, cebB2cMessage);
		CebB2cMessage result;
		if(cebB2cMessage.isHna()){
			result = (CebB2cMessage) cebB2cBankServiceClientHna.query(cebB2cMessage);
		}else{
			result = (CebB2cMessage) cebB2cBankServiceClient.query(cebB2cMessage);
		}
		result.setOutStlmCd(BankConstants.BANK_LOGO_CEB);
		BankLogUtils.printB2CManagerQueryReturnLog(result);
		return result;
	}
	
	
	private CebB2cMessage buildMessage(BaseMessage message) {
		CebB2cMessage cebB2cMessage = (CebB2cMessage) message;	
		cebB2cMessage.setTransId(cebConfig.get("CEB.B2C.TRANSID"));
		cebB2cMessage.setMerchantId(cebB2cMessage.getMerID());
        // 光大借贷分离判断
        if (!cebB2cMessage.isSupportCredit()) {
            cebB2cMessage.setMerchantId("355010000083");
        }
		cebB2cMessage.setMerUrl(cebB2cMessage.getPayRuturnUrl());// 通知商户URL
		cebB2cMessage.setBankUrl(cebB2cMessage.getPayUrl());
		cebB2cMessage.setCurrencyType(cebConfig.get("CEB.CURRENCYTYPE"));
		cebB2cMessage.setMerUrl1(cebB2cMessage.getPayNotifyUrl());	
		return cebB2cMessage;
	}
	
	public String buildPayPlainStr(CebB2cMessage message) {
		StringBuffer sb = new StringBuffer(512);
		sb.append("transId=").append(message.getTransId()).append(SEPARATOR)
		.append("merchantId=").append(message.getMerchantId())
		.append(SEPARATOR).append("orderId=")
		.append(message.getOrderId()).append(SEPARATOR)
		.append("transAmt=").append(message.getAmount())
		.append(SEPARATOR).append("transDateTime=")
		.append(message.getOrderDate()).append(SEPARATOR)
		.append("currencyType=").append(message.getCurrencyType())
		.append(SEPARATOR).append("customerName=")
		.append(message.getCustomerName()).append(SEPARATOR)
		.append("productInfo=").append(message.getProductInfo())
		.append(SEPARATOR).append("customerEMail=")
		.append(message.getCustomerEmail()).append(SEPARATOR)
		.append("merURL=").append(message.getMerUrl())
		.append(SEPARATOR).append("merURL1=")
		.append(message.getMerUrl1()).append(SEPARATOR)
		.append("payIp=").append(message.getPayIp()).append(SEPARATOR)
		.append("msgExt=").append(message.getMsgExt());
		return sb.toString();
	}

	
	public String buildNotifyBankInfo(CebB2cMessage message){
		StringBuffer notifyPlain = new StringBuffer();
		notifyPlain.append("Plain=");
		notifyPlain.append("merchantId=").append(message.getMerchantId()).append(SEPARATOR);
		notifyPlain.append("orderId=").append(message.getOrderId()).append(SEPARATOR);
		notifyPlain.append("transDateTime=").append(message.getTransDateTime()).append(SEPARATOR);
		notifyPlain.append("procStatus=").append("1").append(SEPARATOR);
		notifyPlain.append("merURL2=").append(cebConfig.get("CEB.B2C.MERURL2"));
		return notifyPlain.toString();
	}
	
	private CebB2cMessage buildQueryMessage(CebB2cMessage cebB2cMessage) {
		cebB2cMessage.setTransId(cebConfig.get("CEB.B2C.QUERY.TRANSID"));
		cebB2cMessage.setOriginalTransId(cebConfig.get("CEB.B2C.TRANSID"));
		cebB2cMessage.setMerchantId(cebB2cMessage.getMerID());
		// 光大对账借贷分离判断
        if (!cebB2cMessage.isSupportCredit()) {
            cebB2cMessage.setMerchantId("355010000083");
        }
		cebB2cMessage.setMerUrl(cebConfig.get("CEB.B2C.MERURL"));// 通知商户URL
		cebB2cMessage.setBankUrl(cebB2cMessage.getQueryUrl());
		cebB2cMessage.setCurrencyType(cebConfig.get("CEB.CURRENCYTYPE"));
		return cebB2cMessage;
	}
	
	public String buildQueryPlainStr(CebB2cMessage message) {
		StringBuffer paraMap = new StringBuffer();
		paraMap.append("transId=").append(message.getTransId())
		.append(SEPARATOR).append("merchantId=")
		.append(message.getMerchantId()).append(SEPARATOR)
		.append("originalorderId=")
		.append(message.getOriginalorderId()).append(SEPARATOR)
		.append("originalTransDateTime=")
		.append(message.getOriginalTransDateTime()).append(SEPARATOR)
		.append("originalTransAmt=")
		.append(message.getAmount()).append(SEPARATOR)
		.append("merURL=").append(message.getMerUrl());
		return paraMap.toString();
	}



}
